#include "UdpMulticastReceiver.h"
#include <QHostAddress>
#include <QDebug>
#include<QDataStream>
UdpMulticastReceiver::UdpMulticastReceiver(QObject *parent)
    : QObject(parent), udpSocket1(new QUdpSocket(this)), udpSocket2(new QUdpSocket(this)),
      filePls(nullptr), fileDat(nullptr), isRunning(false)
{
    checkAndCreateDataDir();
}

void UdpMulticastReceiver::start()
{
    if (isRunning) return;
    initializeSocket(udpSocket1, 10001, "224.1.2.3");
    //initializeSocket(udpSocket2, 9200, "239.0.0.1");
    connect(udpSocket1, &QUdpSocket::readyRead, this, [this]() { readPendingDatagrams(udpSocket1); });
    //connect(udpSocket2, &QUdpSocket::readyRead, this, [this]() { readPendingDatagrams(udpSocket2); });

    isRunning = true;
}

void UdpMulticastReceiver::start_wt()
{
    createNewFile();
    //connect(udpSocket1, &QUdpSocket::readyRead, this, [this]() { readPendingDatagrams(udpSocket1); });
}
void UdpMulticastReceiver::stop()
{
    if (!isRunning) return;

    udpSocket1->abort();
    //udpSocket2->abort();
    delete udpSocket1;
    //delete udpSocket2;
    udpSocket1 = nullptr;
    //udpSocket2 = nullptr;

    mutex.lock();
    if (filePls) {
        filePls->close();
        delete filePls;
        filePls = nullptr;
    }

    if (fileDat) {
        fileDat->close();
        delete fileDat;
        fileDat = nullptr;
    }
    mutex.unlock();

    isRunning = false;
}
void UdpMulticastReceiver::stop_wt()
{
    mutex.lock();
    if (filePls) {
        filePls->close();
        delete filePls;
        filePls = nullptr;
    }

    if (fileDat) {
        fileDat->close();
        delete fileDat;
        fileDat = nullptr;
    }
    mutex.unlock();
}

void UdpMulticastReceiver::readPendingDatagrams(QUdpSocket *socket)
{

    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        if (filePls) {
            processReceivedData(datagram);
        }
    }
}

void UdpMulticastReceiver::initializeSocket(QUdpSocket *socket, quint16 port, const QString &multicastGroup)
{
    // 绑定到 AnyIPv4 地址
    socket->bind(QHostAddress::AnyIPv4, port, QUdpSocket::ShareAddress);
    socket->joinMulticastGroup(QHostAddress(multicastGroup));
}

void UdpMulticastReceiver::processReceivedData(const QByteArray &data) {
    // 检查包头是否为0xAA55
    quint16 header = (data[0] << 8) + data[1];
    if (header == 0xAA55) {
        // 锁定互斥体
        mutex.lock();

        // 只处理前34个字节作为.pls文件数据部分
        QByteArray plsData = data.mid(0, 40);

        QDataStream stream(&plsData, QIODevice::ReadOnly);
        stream.setByteOrder(QDataStream::LittleEndian); // 根据数据的实际字节序设置
        // 读取数据
        quint16 first;
        qint64 second;
        quint32 third, fourth, fifth, sixth, seventh, eighth;
        stream >> first>> second >> third >> fourth >> fifth >> sixth >> seventh >> eighth;
        if(mowei==0)
        {
            mowei=seventh;
        }

        // 剩余的数据作为.dat文件数据部分
        QByteArray datData = data.mid(40);

        // 写入.pls文件
        if (filePls) {
            wenjian_changdu = filePls->size();
            if (filePls->size() > fileSizeLimit) {
                createNewFile();
            } else {
                filePls->write(plsData.data(),40);
                //qDebug() << "pls in hex:" << plsData.toHex();
            }
        }else {
            return;
        }

        // 写入.dat文件
        if (fileDat) {
            fileDat->seek((seventh-mowei)*4);
            fileDat->write(datData.data(),datData.length());
        }else {
            return;
        }
        // 解锁互斥体
        mutex.unlock();
    } else {
        // 如果包头不是0xAA55，这里可以根据需要处理其他类型的数据包
        //qDebug()<<header;
    }
}

void UdpMulticastReceiver::createNewFile()
{
    mowei=0;
    QDateTime now = QDateTime::currentDateTime();
    QString baseName = now.toString("yyyyMMddhhmmss");

    QString filePathPls = dataPath + QDir::separator() + baseName + ".pls";
    QString filePathDat = dataPath + QDir::separator() + baseName + ".dat";

    if (filePls) {
        filePls->close();
        delete filePls;
    }

    if (fileDat) {
        fileDat->close();
        delete fileDat;
    }

    QFile *newFilePls = new QFile(filePathPls);
    QFile *newFileDat = new QFile(filePathDat);

    if (newFilePls->open(QIODevice::WriteOnly)) {
        filePls = newFilePls;
        fileNamePls = baseName + ".pls";
    } else {
        qDebug() << "Failed to open file:" << filePathPls;
        delete newFilePls;
    }

    if (newFileDat->open(QIODevice::WriteOnly)) {
        fileDat = newFileDat;
        fileNameDat = baseName + ".dat";
    } else {
        qDebug() << "Failed to open file:" << filePathDat;
        delete newFileDat;
    }
}

void UdpMulticastReceiver::checkAndCreateDataDir()
{
    dataPath = QDir::currentPath() + QDir::separator() + "data";
    QDir dir(dataPath);
    if (!dir.exists()) {
        dir.mkpath(dataPath);
    }
}

bool UdpMulticastReceiver::checkHeader(const QByteArray &data, quint16 expectedHeader)
{
    if (data.size() >= 2) {
        quint16 header = (data[0] << 8) + data[1];
        return header == expectedHeader;
    }
    return false;
}
